package com.sunwhite.jdbc.MyJdbc;

import com.sunwhite.jdbc.MyJdbc.interfaces.MyJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyJdbcTemplate implements MyJdbc {

  private static Connection connection;

  public List<Map<String, Object>> executeQuery(String sql) throws Exception {
    ArrayList<Map<String, Object>> list = new ArrayList<>();
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    ResultSet resultSet = preparedStatement.executeQuery();
    Map<String, Object> map = null;
    System.out.println("resultSet" + resultSet.toString());
    while (resultSet.next()) {
      map = new HashMap<>();
      Integer rowCount = resultSet.getMetaData().getColumnCount();
      System.out.println("rowCount" + rowCount);
      for (Integer i = 1; i <= rowCount; i++) {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        String rowName = resultSetMetaData.getColumnName(i);
        map.put(rowName, resultSet.getString(rowName));
      }
      list.add(map);
    }
    resultSet.close();
    preparedStatement.close();
    return list;
  }

  @Override
  public int executeUpdate(String sql) throws Exception {

    return 0;
  }

  public static Connection getConnection() {
    return connection;
  }

  public static void setConnection(Connection connection) {
    MyJdbcTemplate.connection = connection;
  }
}
